<template>
    <div class="index-bind">
        <div class="index-bind-height">
          <div class="index-map">
            <div class="index-map-content">
              <baidu-map :center="center" :zoom="zoom" @ready="handler" :style="{height:height+'px'}"  :scroll-wheel-zoom='true'>
                <bm-geolocation anchor="BMAP_ANCHOR_TOP_RIGHT" :showAddressBar="false" :autoLocation="true"
                                @locationSuccess="getLoctionSuccess" @locationError="getLocationError">
                </bm-geolocation>
                <!-- 自定义定位图标覆盖物 -->
                <bm-marker :position="autoLocationPoint" v-if="initLocation">
                </bm-marker>
                <div v-for="marker in markers">
                  <bm-marker v-if="marker.carOwner===1" :position="{lng: marker.longitude, lat: marker.latitude}"
                             :title="marker.name" @click="getMarkedUserInformation(marker)"
                             :icon="{url:require('../../../static/images/car.png'),size:{width:32,height:32}}">
                    <bm-info-window v-if="status===1" :show="marker.show"
                                    @close="infoWindowClose(marker)" @open="infoWindowOpen(marker)"
                                    :position="{lng: marker.lng, lat: marker.lat}">
                      <div class="bm_info_window_text">姓名：{{marker.name}}</div>
                      <div class="bm_info_window_text">部门：{{marker.text}}</div>
                      <div class="bm_info_window_text">车牌：{{marker.carNum}}</div>
                      <div v-if="marker.comment" class="bm_info_window_text">备注：{{marker.comment}}</div>
                      <div class="bm_info_window_text">电话：<a :href="'tel:'+marker.phone" style="text-decoration:underline">{{marker.phone}}</a></div>
                      <div class="bm_info_window_text">状态：已载{{marker.loadingNum}}/{{marker.loadNum}}</div>
                      <div class="zai-btn">
                        <div v-if="marker.loadingNum < marker.loadNum && carOwner===0 && !hasCar" class="btn-bottom-right-bm-info">
                          <span  class="btn-bottom-right-style" @click="passRequestCar(marker)">求搭载</span>
                        </div>
                        <div v-if="carOwner===0 && hasCar && driverPhone === marker.phone" class="btn-bottom-right">
                          <span  class="btn-bottom-right-style" @click="terminateContract(marker)">取消搭载</span>
                        </div>
                      </div>
                    </bm-info-window>
                  </bm-marker>
                  <bm-marker v-if="marker.carOwner===0" :position="{lng: marker.longitude, lat: marker.latitude}"
                             :title="marker.name" @click="getMarkedUserInformation(marker)"
                             :icon="{url:require('../../../static/images/person.png'),size:{width:32,height:32}}">
                    <bm-info-window v-if="status===1" :show="marker.show" @close="infoWindowClose(marker)" @open="infoWindowOpen(marker)"
                                    :position="{lng: marker.lng, lat: marker.lat}">
                      <div class="bm_info_window_text">姓名：{{marker.name}}</div>
                      <div class="bm_info_window_text">部门：{{marker.text}}</div>
                      <div v-if="marker.comment" class="bm_info_window_text">备注：{{marker.comment}}</div>
                      <div class="bm_info_window_text">电话：<a :href="'tel:'+marker.phone" style="text-decoration:underline">{{marker.phone}}</a></div>
                      <div class="bm_info_window_text" v-if="marker.hasCar">状态：拼车成功</div>
                      <div class="bm_info_window_text" v-if="!marker.hasCar ">状态：请求搭载中...</div>
                      <div class="zai-btn">
                        <div v-if="!marker.hasCar && carOwner===1 && loadingNum < loadNum " class="btn-bottom-right-bm-info">
                          <span class="btn-bottom-right-style" @click="carTakePass(marker)">载TA</span>
                        </div>
                        <div v-if="carOwner===1 && marker.hasCar && marker.isMyPass" class="btn-bottom-right">
                          <span class="btn-bottom-right-style" @click="terminateContract(marker)">取消搭载</span>
                        </div>
                      </div>
                    </bm-info-window>
                  </bm-marker>
                </div>
              </baidu-map>
            </div>
          </div>
          <div class="top-div">
            <div class="top-img">
              <img class="top-icon" @click="targetUserInfo()" src="../../../static/images/wo.png"/>
            </div>
          </div>
          <div class="footer-fixed">

            <div class="footer-bottom" v-if="status===0" >
              <div class="info">共{{carNumber}}车主,{{passNumber}}乘客,已有{{carNumbered}}车主接送{{passNumbered}}乘客</div>
              <div class="btn-bottom">
                <div class="btn-bottom-left" @click="targetLogin(1)">
                  <span class="btn-bottom-style">我有车</span>
                </div>
                <div class="btn-bottom-right" @click="targetLogin(0)">
                  <span class="btn-bottom-right-style">求搭车</span>
                </div>
              </div>
            </div>

            <div class="btn-bottom" style="height:4rem" v-if="status===1" >
              <!--<div class="info" v-if="carOwner===1">已接{{loadingNum}}/{{loadNum}}人</div>-->
              <!--<div class="info" v-if="carOwner===0 && hasCar===0">乘客</div>-->
              <!--<marquee class="info" v-if="carOwner===0 && hasCar===1" scrollamount="5" onMouseOut="this.start()" onMouseOver="this.stop()">{{driverName}}已经带你</marquee>-->
              <div class="btn-bottom-left">
                <!--<span v-if="carOwner===1"  class="btn-bottom-style"></span>-->
                <span class="btn-bottom-style" @click="refreshIndexView" >刷新</span>
                <!--<span v-if="carOwner===0 && hasCar===0"  class="btn-bottom-style">尚未拼车</span>-->
                <!--<marquee v-if="carOwner===0 && hasCar===1" scrollamount="5" onMouseOut="this.start()" onMouseOver="this.stop()" class="btn-bottom-style">{{driverName}}已经带你</marquee>-->
              </div>
              <div v-if="carOwner===0 && hasCar===0" class="text-style">尚未拼车</div>

              <div class="text-style" v-if="carOwner===0 && hasCar===1">{{driverName}}已经带你</div>
              <div v-if="carOwner===1" class="text-style">已接{{loadingNum}}/{{loadNum}}人</div>

              <div class="right">
                <div class="btn-bottom-right" @click="targetList">
                  <span class="btn-bottom-right-style">列表</span>
                </div>
                <div v-if="newMessageCount !== 0" class="circle" @click="targetList">{{newMessageCount}}</div>
              </div>
            </div>
          </div>
        </div>
    </div>
</template>

<script>
    import Vue from 'vue'
    import {  Swipe, SwipeItem,Dialog,Toast} from 'vant';
    import { mapState,mapActions } from "vuex"
    import {toast} from "../../tools";


    Vue.use(Swipe).use(SwipeItem).use(Dialog).use(Toast)
    export default {
        name: "index",
        data() {
          return {
            status:0,//0未登录,1已经登录


            //已登录状态下的参数
            carOwner:0,//1车主,0乘客
            phone: 17784454983,
            name:"小傻瓜",
            department:1,
            address:"中和街道黄金时代",
            longitude:11,
            latitude:12,
            carNum:"川A123",//车主
            loadNum:4,//车主可载客
            loadingNum:3,//车主已载客
            comment:"我是好人，请上车",
            newMessageCount:5,

            //已登录状态下的乘客参数
            hasCar:0,
            driverName:"张三",
            driverPhone:"",
            passData:[],

            //未登录状态参数
            carNumber:0,
            passNumber:0,
            carNumbered:0,
            passNumbered:0,

            mod_map:'',
            center: '',
            zoom:12,
            showInfo:true,
            mod_title:'hello',
            markersCarOwner:[],
            markersPasser:[],
            markers: [],
            autoLocationPoint: {lng: 0, lat: 0},
            initLocation: false,
            height:'',

            departments:[
              {
                text:'GCS-APPD-CD',
                id:0
              },
              {
                text:'GCS-SYSD-CD',
                id:1
              },
              {
                text:'GCS-SPMD-CD',
                id:2
              },
              {
                text:'SPC-SPMD-CD',
                id:3
              },
              {
                text:'VAL-GCS-CD',
                id:4
              },
              {
                text:'HR&Admin-CD',
                id:5
              }
            ],
            taPhone:0
          }
        },
      computed: {

      },
        components: {
          "van-swipe":Swipe,
          "van-swipe-item":SwipeItem,
          [Dialog.Component.name]: Dialog.Component,
        },
      mounted: function () {
        this.height = window.innerHeight
        console.log('height:', window.innerHeight)
        if (this.$route.query.status === 1 || this.$route.query.status === '1') {
          this.status = 1
          if (this.$route.query.id === 1 || this.$route.query.id === '1') {
            this.carOwner = 1
          } else {
            this.carOwner = 0
          }
          console.log('that： ' + this.carOwner)
          this.phone = this.$route.query.phone
          this.taPhone = localStorage.getItem('taPhone')
          localStorage.removeItem("taPhone")
        }else {
          this.getTotalPassCarNum()
        }
        this.getUserSimpleList()

      },
        methods:{
          refreshIndexView(){
            this.$router.go(0);
          },
          getLoctionSuccess(){
          },
          getLocationError(){
          },

          // clickMark(marker) {
          //   // console.log("click mark",marker.name)
          //   // if(this.carOwner===1 || this.carOwner==="1"){
          //   //   if(marker.carOwner ===1 || marker.carOwner ==="1"){
          //   //     return;
          //   //   }
          //   // }else {
          //   //   if(marker.carOwner ===1 || marker.carOwner ==="1"){
          //   //   }else {
          //   //     return;
          //   //   }
          //   // }
          //   console.log(marker);
          //   console.log("测试")
          //   this.getMarkedUserInformation(marker);
          // },
          //获取统计信息
          getMarkedUserInformation: function (marker) {
            console.log("getMarkedUserInformation2 ",marker)
            console.log("getMarkedUserInformation",this.markers)
            // marker.show = false
            let that_marker = marker;
            let that = this;
            this.$httpGetService('/getUserInformation',{
              carOwner:marker.carOwner,
              phone:marker.phone
            }).then(res => {
              console.log(res);
              that_marker.name = res.name
              that_marker.department=that.departments[res.department]
              that_marker.longitude=res.longitude
              that_marker.latitude=res.latitude
              that_marker.comment = res.comment;
              // Vue.set(that.markers[i],'comment',"")
              // that.comment=res.comment
              // that.newMessageCount=res.newMessageCount
              if(that_marker.carOwner===1 || that_marker.carOwner==="1"){
                that_marker.carNum = res.carNum
                that_marker.loadNum = res.loadNum
                that_marker.loadingNum = res.loadingNum;
                that_marker.passData=res.passData;
              }else {
                that_marker.hasCar=res.hasCar
                that_marker.driverName=res.driverName
                that_marker.driverPhone =res.driverPhone
              }
              that.changeMarksData();
              // marker.show = true
              Vue.set(marker,'show',true)


            }).catch(err => {
              console.log(err)
            })
          },
          getMarkedUserInformationNotShow: function (marker) {
            let that_marker = marker;
            let that = this;
            this.$httpGetService('/getUserInformation',{
              carOwner:that_marker.carOwner,
              phone:that_marker.phone
            }).then(res => {
              console.log(res);
              that_marker.name = res.name
              that_marker.department=that.departments[res.department]
              that_marker.longitude=res.longitude
              that_marker.latitude=res.latitude
              // Vue.set(that.markers[i],'comment',"")
              that_marker.comment = res.comment;
              // Vue.set(that.markers[i],'comment',"")
              // that.comment=res.comment
              // that.newMessageCount=res.newMessageCount
              if(that_marker.carOwner===1 || that_marker.carOwner==="1"){
                that_marker.carNum = res.carNum
                that_marker.loadNum = res.loadNum
                that_marker.loadingNum = res.loadingNum;
                that_marker.passData=res.passData;
              }else {
                that_marker.hasCar=res.hasCar
                that_marker.driverName=res.driverName
                that_marker.driverPhone =res.driverPhone
              }
              that.getUserInformation();
            }).catch(err => {
              console.log(err)
            })
          },

          infoWindowClose(marker) {
            console.log("close mark",marker.name)
            marker.show = false
          },
          infoWindowOpen(marker) {
            console.log("open mark",marker.name)
            marker.show = true

          },
          handler ({BMap, map}) {
            let _this = this;	// 设置一个临时变量指向vue实例，因为在百度地图回调里使用this，指向的不是vue实例；
            var geolocation = new BMap.Geolocation();
            geolocation.enableSDKLocation();
            geolocation.getCurrentPosition(function(r){
              // console.log('hyf',geolocation.getStatus());
              // console.log('hyf2',geolocation.BMAP_STATUS_SUCCESS);
              // console.log('hyf3',BMap);
              console.log(r)

              // alert(JSON.stringify(this.getStatus()))
              if(this.getStatus() == BMAP_STATUS_SUCCESS) {
                console.log("accuracy",r.accuracy)
                if(r.accuracy == null ){
                  // alert('请允许该网站获取地理位置信息！');
                  // return;
                  console.log('center:', _this.center)	// 如果这里直接使用this是不行的
                  _this.center = {lng: 104.079337, lat: 30.545151};		// 设置center属性值
                  _this.autoLocationPoint = {lng: 104.079337, lat: 30.545151};		// 自定义覆盖物
                  _this.initLocation = true;
                  console.log('center:', _this.center)	// 如果这里直接使用this是不行的
                }else {
                  // alert(r.accuracy);
                  // 104.079337,30.545151
                  _this.center = {lng: r.longitude, lat: r.latitude};		// 设置center属性值
                  _this.autoLocationPoint = {lng: r.longitude, lat: r.latitude};		// 自定义覆盖物
                  _this.initLocation = true;
                }
              } else {
                // 104.079337,30.545151
                _this.center = {lng: 104.079337, lat: 30.545151};		// 设置center属性值
                _this.autoLocationPoint = {lng: 104.079337, lat: 30.545151};		// 自定义覆盖物
                _this.initLocation = true;
                console.log('center:', _this.center)	// 如果这里直接使用this是不行的
              }

            },{enableHighAccuracy: true})
            console.log(map)
          },
          targetUserInfo(){
            this.$router.push({
              name:"userInfo",
              query:{
                status:1,
                id:this.carOwner,
                phone:this.phone
              }
            });
          },
          targetList(){
            console.log("targetList")
            this.$router.push({
              name:"ownerList",
              query:{
                id:this.carOwner,
                phone:this.phone
              }
            })
          },

          targetLogin(id){
            this.$router.push({
              name:'login',
              query:{
                id:id
              }
            })
          },
          onChange(index){
            this.current = index
          },
          //乘客
          getPasserSimpleList: function () {
            let that = this;
            this.$httpGetService('/getUserSimpleList',{
              listCode:0
            }).then(res => {
              console.log(res);
              that.markersPasser =  res
            }).catch(err => {
              console.log(err)
            })
          },
          //所有人的列表
          getUserSimpleList: function () {
            let that = this;
            this.$httpGetService('/getUserSimpleList',{
              listCode:2
            }).then(res => {
              // console.log(res);
              that.markers =  res
              let m = -1;
              for(let i=0;i<that.markers.length;i++){
                if(that.markers[i].phone === that.taPhone){
                  Vue.set(that.markers[i],'show',true)
                  that.center = {lng: that.markers[i].longitude, lat: that.markers[i].latitude};		// 设置center属性值
                  that.autoLocationPoint = {lng: that.markers[i].longitude, lat: that.markers[i].latitude};		// 自定义覆盖物
                  that.initLocation = true;
                  // that.getMarkedUserInformationNotShow2();
                  that.taPhone = ""
                  m = i;
                }else {
                  Vue.set(that.markers[i],'show',false)
                }
                Vue.set(that.markers[i],'text',that.departments[that.markers[i].departmentId].text)
                if(that.status === 1 && that.carOwner === 1 && that.passData.length > 0){
                  for (let j=0;j< that.passData.length;j++){
                    if(that.passData[j].passPhone === that.markers[i].phone){
                      Vue.set(that.markers[i],'isMyPass',true)
                    }else {
                      Vue.set(that.markers[i],'isMyPass',false)
                    }
                  }
                }else {
                  Vue.set(that.markers[i],'isMyPass',false)
                }
                Vue.set(that.markers[i],'text',that.departments[that.markers[i].departmentId].text)
                Vue.set(that.markers[i],'comment',"")

              }
              console.log("列表")
              console.log(that.markers);
              if(that.status === 1){
                if(m !== -1){
                  that.getMarkedUserInformationNotShow(that.markers[m])
                }else {
                  that.getUserInformation()
                }

              }
            }).catch(err => {
              console.log(err)
            })
          },
          changeMarksData(){
            for(let i=0;i<this.markers.length;i++){
              console.log()
              if(this.status === 1 && this.carOwner === 1 && this.passData.length > 0){
                for (let j=0;j< this.passData.length;j++){
                  if(this.passData[j].passPhone === this.markers[i].phone){
                    this.markers[i].isMyPass = true;
                    Vue.set(this.markers[i],'isMyPass',true)
                  }else {
                    this.markers[i].isMyPass = false;
                    Vue.set(this.markers[i],'isMyPass',false)
                  }
                }
              }else {
                this.markers[i].isMyPass = false;
              }
            }
            console.log("getUserInformation",this.markers)
          },
          //去接他
          carTakePass(marker) {
            let that = this;
            marker.show = false
            this.$httpPostService('/carTakePass',{
                carPhone:this.phone,
                passPhone:marker.phone
            }).then(res => {
              console.log(res);
              if(res.error_code === 0){
                toast("发送失败")
              }else if(res.error_code === 1){
                that.getMarkedUserInformationNotShow(marker);
                toast("发送成功")
              }else if(res.error_code === 2){
                toast("已经发送过了")
              }else if(res.error_code === 3){
                toast("司机承载量已满")
              }else {
                toast("发送失败")
              }
            }).catch(err => {
              console.log(err)
            })
          },
          //求带
          passRequestCar(marker) {
            let that = this;
            marker.show = false
            this.$httpPostService('/passRequestCar',{
              carPhone:marker.phone,
              passPhone:this.phone
            }).then(res => {
              console.log(res);

              if(res.error_code === 0){
                toast("发送失败")
              }else if(res.error_code === 1){
                toast("发送成功")
                that.getMarkedUserInformationNotShow(marker);
                // marker.hasCar = true;
                // marker.driverName = that.name;
              }else if(res.error_code === 2){
                toast("已经发送过了")
              }else if(res.error_code === 3){
                toast("司机承载量已满")
              }else {
                toast("发送失败")
              }
            }).catch(err => {
              console.log(err)
            })
          },
          //获取统计信息
          getTotalPassCarNum: function () {
            let that = this;
            this.$httpGetService('/getTotalPassCarNum').then(res => {
              console.log(res);
              that.carNumber=res.carNumber;
              that.passNumber=res.passNumber;
              that.carNumbered=res.carNumbered;
              that.passNumbered=res.passNumbered;
            }).catch(err => {
              console.log(err)
            })
          },
          //获取用户信息
          getUserInformation: function () {
            let that = this;
            this.$httpGetService('/getUserInformation',{
              carOwner:this.carOwner,
              phone:this.phone
            }).then(res => {
              console.log(res);
              console.log("that： "+that.carOwner);
              that.name = res.name
              that.department=that.departments[res.department]
              that.longitude=res.longitude
              that.latitude=res.latitude
              that.comment=res.comment
              that.newMessageCount=res.newMessageCount
              if(that.carOwner===1 || that.carOwner==="1"){
                that.carNum = res.carNum
                that.loadNum = res.loadNum
                that.loadingNum = res.loadingNum
                that.passData = res.passData
              }else {
                that.hasCar=res.hasCar
                that.driverName=res.driverName
                that.driverPhone = res.driverPhone
              }
              console.log("getUserInformation",that.markers)

              that.changeMarksData();
            }).catch(err => {
              console.log(err)
            })
          },
          terminateContract(item) {
            item.show =false;
            console.log("terminateContract",item)

            let that = this;
            this.$httpPostService('/terminateContract',{
              carOwner:this.carOwner,
              passPhone:this.carOwner===1?item.phone:this.phone,
              carPhone:this.carOwner===1?this.phone:item.phone
            }).then(res => {
              console.log(res);
              if(res.error_code === 0){
                toast("请检查参数")
              }else if(res.error_code === 1 || res.error_code === 2){
                if(item.isMyPass){
                  item.isMyPass = false;
                }
                console.log("terminateContract2",item)
                that.getMarkedUserInformationNotShow(item)
                toast("已取消搭载")
              }
            }).catch(err => {
              console.log(err)
              // Toast("获取消息列表失败")
            })
          },
          startMove () {
            let timer = setTimeout(() => {
              if (this.number === this.textArr.length -1) {
                this.number = 0;
              } else {
                this.number += 1;
              }
              this.startMove();
            }, 2000); // 滚动不需要停顿则将2000改成动画持续时间
          }
        },



    }
</script>
<style scoped lang="less" src="../../assets/less/indexBind.less"></style>
<style lang="less">
</style>


